package com.soecode.music_collector.collector.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.soecode.music_collector.collector.BaseRankCollector;
import com.soecode.music_collector.constants.UrlConst;
import com.soecode.music_collector.pojo.HotSinger;
import com.soecode.music_collector.pojo.Rank;
import com.soecode.music_collector.util.HttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.text.MessageFormat;

public class NeteaseRankCollector implements BaseRankCollector {

    @Override
    public Rank collect(String url) throws IOException {
        return getRank(url);
    }

    @Override
    public Rank getRank(String rankUrl) throws IOException {
        Rank rank = new Rank();
        String body = HttpClientUtil.get(rankUrl);
        Document doc = Jsoup.parse(body);
        rank.setScope(doc.select("a[class=current]").attr("title"));
        rank.setUpdateTime(doc.select("span[class=rank_update]").text());
        String jsonString=doc.getElementById("song-list-pre-data").text();
        final JSONArray jsonObject = (JSONArray) JSON.parse(jsonString);
        jsonObject.stream().limit(20).forEach(x -> buildRank(x,rank));
        return rank;
    }

    private <T> void buildRank(T t, Rank rank){
        final JSONObject jsonObject = (JSONObject) t;
        final String songName = jsonObject.getString("name");
        final String songId = jsonObject.getString("id");
        final String singerName = ((JSONObject)((JSONArray)jsonObject.get("artists")).get(0)).getString("name");
        rank.getHotSingerList().add(HotSinger.builder()
                .name(MessageFormat.format(UrlConst.NETEASE_SONG_URL,songId,songName,singerName))
                .build());
    }

    public static void main(String[] args) {
        NeteaseRankCollector collector = new NeteaseRankCollector();
        try {
            for(HotSinger s : collector.collect(UrlConst.HUAYU_NEW_SONG_RANK_URL).getHotSingerList()){
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
